﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace a23_ContextMenu
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void StaticContextMenuOpeningHandler(object sender, ContextMenuEventArgs e)
        {
            var fe = e.Source as FrameworkElement;
            var cm = fe.ContextMenu;
            if(cm.Items.Cast<MenuItem>().Any(mi => (string)mi.Header == "dynamic 4"))
            {
                return;
            }
            cm.Items.Add(new MenuItem { Header = "dynamic 4" });
        }

        int k = 0;

        private void DynamicContextMenuOpeningHandler(object sender, ContextMenuEventArgs e)        
        {
            k++;
            var theMenu = new ContextMenu();
            var mia = new MenuItem { Header = "dynamic 1" + k };
            var mib = new MenuItem { Header = "dynamic 2" + k };
            var mic = new MenuItem { Header = "dynamic 3" + k };
            theMenu.Items.Add(mia);
            theMenu.Items.Add(mib);
            theMenu.Items.Add(mic);

            var fe = e.Source as FrameworkElement;
            fe.ContextMenu = theMenu;
            fe.ContextMenu.IsOpen = true;       //若无此句, 则第一次点击不会弹出contextMenu.
        }

        private void MouseDownHandler(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                k++;

                var theMenu = new ContextMenu();
                var mia = new MenuItem { Header = "left 1" + k };
                var mib = new MenuItem { Header = "left 2" + k };
                var mic = new MenuItem { Header = "left 3" + k };
                theMenu.Items.Add(mia);
                theMenu.Items.Add(mib);
                theMenu.Items.Add(mic);

                var fe = e.Source as FrameworkElement;
                fe.ContextMenu = theMenu;
                fe.ContextMenu.IsOpen = true;       //若无此句, 则第一次点击不会弹出contextMenu.
            }
        }
    }
}
